import {defineStore} from "pinia";
import {ref} from "vue";
import type {Dictionary} from "@/api/detail/type.ts";
import {getIncomeExpenseType, getSourceType} from "@/api/detail";

export const useDetailStore = defineStore("detail", () => {
  // 来源类型
  const sourceTypes = ref<Dictionary[]>([]);

  //收支类型
  const incomeExpenseTypes = ref<Dictionary[]>([]);


  /**
   * 获取字典数据
   */
  async function fetchDictionaries() {
    try {
      const [inExRes, sourceRes] = await Promise.all([
        getIncomeExpenseType(),
        getSourceType()
      ]);
      incomeExpenseTypes.value = inExRes.data;
      sourceTypes.value = sourceRes.data;
    } catch (e) {
      console.error("获取字典数据失败", e);
    } finally {

    }
  }

  /**
   * 根据code获取收支类型
   * @param code
   */
  function getInExTypeByCode(code: number) {
    const e = incomeExpenseTypes.value.find(item => item.code === code);
    if (!e) {
      throw new Error("未找到对应的字典项");
    }
    return e;
  }

  /**
   * 根据code获取来源类型
   * @param code
   */
  function getSourceTypeByCode(code: number) {
    const e = sourceTypes.value.find(item => item.code === code);
    if (!e) {
      throw new Error("未找到对应的字典项");
    }
    return e;
  }


  return {
    // 状态
    sourceTypes,
    incomeExpenseTypes,
    fetchDictionaries,
    getInExTypeByCode,
    getSourceTypeByCode

  };
});
